import static com.googlecode.javacv.cpp.opencv_core.cvAddWeighted;
import static com.googlecode.javacv.cpp.opencv_core.cvCopy;
import static com.googlecode.javacv.cpp.opencv_core.cvGetSize;
import static com.googlecode.javacv.cpp.opencv_highgui.CV_LOAD_IMAGE_COLOR;
import static opencvtest.OpenCVUtils.drawOnImage;
import static opencvtest.OpenCVUtils.loadAndShowOrExit;
import static opencvtest.OpenCVUtils.show;
import static opencvtest.OpenCVUtils.toIplROI;

import java.awt.Color;
import java.awt.Rectangle;
import java.io.File;

import com.googlecode.javacv.cpp.opencv_core.CvMat;
import com.googlecode.javacv.cpp.opencv_core.IplImage;

/**
 * Created with IntelliJ IDEA. User: joey Date: 16/3/14 Time: 下午12:12 To change
 * this template use File | Settings | File Templates.
 */
public class JavaCvRemoveQiNiuWater {

    public static void main(String[] args) throws Exception {

        IplImage image = loadAndShowOrExit(new File("gogopher.jpg"), CV_LOAD_IMAGE_COLOR);

        Rectangle rect = new Rectangle(330, 362, 290, 45);
        show(drawOnImage(image, rect, Color.RED), "Input template");
        IplImage roiImage = image.roi(toIplROI(rect));

        IplImage water = loadAndShowOrExit(new File("logo-2.jpg"), CV_LOAD_IMAGE_COLOR);
        CvMat waterMat = water.asCvMat();
        System.out.println(water.depth());
        System.out.println(water.nChannels());

        IplImage roiImage2 = IplImage.create(cvGetSize(water), water.depth(), 3);
        cvCopy(roiImage, roiImage2);

        CvMat roiMat = roiImage2.asCvMat();

        int n = roiMat.rows() * roiMat.cols() * roiMat.nChannels();

        for (int i = 0; i < n; i++) {
            int wv = (int) waterMat.get(i);
            int rv = (int) roiMat.get(i);
            if (wv <= 240) {
                roiMat.put(i, rv - (wv - (255 - wv)) * 0.5);
                System.out.println(rv - (wv - (255 - wv)) * 0.5);
            } else {
                roiMat.put(i, rv);
            }
        }

        show(roiMat, "roi mat");

        // cvAdd(waterMat, roiImage, image, null);
        cvAddWeighted(roiImage2, 1.0, roiImage, 0.0, 0.0, image);

        image.roi(null);
        show(image, "removed water image");

    }

}
